package info.hexin.aop2;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;

public class Generator {
    private static AccountGeneratorClassLoader classLoader = new AccountGeneratorClassLoader();
    private static Class secureAccountClass;

    public static AccountAsm generateSecureAccount() throws Exception {
        if (null == secureAccountClass) {
            ClassReader cr = new ClassReader("info.hexin.aop2.AccountAsm");
            System.out.println(">>>>" + cr.getClassName());
            ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            cr.accept(new ClassAdapter(cw), 0);
            byte[] data = cw.toByteArray();
            System.out.println(data.length);
            secureAccountClass = classLoader.defineClassFromClassFile("info.hexin.aop2.AccountAsm", data);
        }
        return (AccountAsm) secureAccountClass.newInstance();
    }

    private static class AccountGeneratorClassLoader extends ClassLoader {
        public Class defineClassFromClassFile(String className, byte[] classFile) throws ClassFormatError {
            return defineClass(className, classFile, 0, classFile.length);
        }
    }
}
